import 'package:f_demo/bloc/index.dart';
import 'package:f_demo/ui/widgets/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  Animation<double> formTranslation;
  Animation<double> navAnimation;
  Animation<Offset> textTranslation;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _buildAnimation(); // 此处代码省略，见上面
  }

  void _buildAnimation() {
    if (navAnimation == null) {
      navAnimation = ModalRoute.of(context).animation;
//      formTranslation = Tween(begin: ScreenUtil.getInstance().setHeight(1334), end: ScreenUtil.getInstance().setHeight(200)).animate(
//        CurvedAnimation(parent: navAnimation, curve: Interval(0.34, 0.84, curve: Curves.ease)),
//      );

      textTranslation = Tween(
        begin: Offset(0.0, 1.0),
        end: Offset(0.0, 0.0),
      ).animate(
        CurvedAnimation(
          parent: navAnimation,
          curve: Interval(0.34, 0.84, curve: Curves.ease),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            width: ScreenUtil.getInstance().setWidth(750),
            height: ScreenUtil.getInstance().setHeight(1334),
          ),
          BgArcWidget(bgColor: Theme.of(context).primaryColor),
          SafeArea(
            child: IconButton(
              icon: Icon(
                Icons.close,
                color: Colors.white,
                size: 30,
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
          ),
          AnimatedBuilder(
            animation: navAnimation,
            builder: (BuildContext context, Widget child) {
              return Positioned(
                top: ScreenUtil.getInstance().setHeight(250),
                child: FractionalTranslation(
                  translation: textTranslation.value,
                  child: _LoginForm(),
                ),
              );
            },
          ),
          Positioned(
            top: ScreenUtil.getInstance().setHeight(190),
            left: ScreenUtil().setWidth(305),
            child: Hero(
              tag: 'user_avatar',
              child: CircleAvatar(
                radius: ScreenUtil().setWidth(70),
                child: ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setWidth(80))),
                  child: Image.network('https://gitee.com/xushuai1231/images/raw/master/icon-1024.png'),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

class _LoginForm extends StatefulWidget {
  @override
  __LoginFormState createState() => __LoginFormState();
}

class __LoginFormState extends State<_LoginForm> {
  OauthBloc _oauthBloc;

  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();
  bool _loading = false;

  @override
  void initState() {
    _oauthBloc = BlocProvider.of<OauthBloc>(context);
    super.initState();
  }

  _login() async {
    if ((_formKey.currentState as FormState).validate() && !_loading) {
      _oauthBloc.dispatch(OauthLoginEvent(username: _usernameController.text, password: _passwordController.text));
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<OauthBloc, OauthState>(
      listener: (context, state) {
        if (state is OauthLoginLoadingState) {
          setState(() {
            _loading = true;
          });
        } else if (state is OauthLoginFailureState) {
          setState(() {
            _loading = false;
            showToast("用户名或密码错误");
          });
        } else if (state is OauthLoginSuccessState) {
          Navigator.pop(context);
        }
      },
      child: Container(
          width: ScreenUtil.getInstance().setWidth(650),
          padding: EdgeInsets.all(20),
          margin: EdgeInsets.only(left: ScreenUtil.getInstance().setWidth(50)),
          decoration: BoxDecoration(
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(200, 200, 200, 1),
                blurRadius: 10,
                offset: Offset(0, 10),
              )
            ],
          ),
          child: Column(
            children: <Widget>[
              Form(
                key: _formKey,
                autovalidate: true,
                child: Column(
                  children: <Widget>[
                    TextFormField(
                      decoration: InputDecoration(
                        labelText: "用户名",
                        prefixIcon: Icon(Icons.person),
                      ),
                      validator: (t) {
                        return t.trim().length > 0 ? null : "用户名不能为空";
                      },
                    ),
                    TextFormField(
                      decoration: InputDecoration(
                        labelText: "密码",
                        prefixIcon: Icon(Icons.lock),
                      ),
                      obscureText: true,
                      validator: (t) {
                        return t.trim().length > 0 ? null : "密码不能为空";
                      },
                    )
                  ],
                ),
              ),
              Container(
                width: ScreenUtil.getInstance().setWidth(610),
                margin: EdgeInsets.only(top: 40),
                child: RaisedButton(
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(100)),
                  onPressed: () {
                    _login();
                  },
                  child: _loading
                      ? SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            valueColor: AlwaysStoppedAnimation(Colors.white),
                          ),
                        )
                      : Text('登录', style: TextStyle(color: Colors.white)),
                  color: Theme.of(context).primaryColor,
                ),
              )
            ],
          )),
    );
  }
}
